
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>数据库工具 &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="模型关联 API 用法示例" href="examples/index.html" />
    <link rel="prev" title="数据库访问优化" href="optimization.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="optimization.html" title="数据库访问优化">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="examples/index.html" title="模型关联 API 用法示例">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-instrumentation">
            
  <div class="section" id="s-database-instrumentation">
<span id="database-instrumentation"></span><h1>数据库工具<a class="headerlink" href="#database-instrumentation" title="永久链接至标题">¶</a></h1>
<p>为了帮助你更好的理解并控制由你的代码所产生的数据库查询,Django提供了一个钩子函数,在这个钩子函数中你可以在数据库查询方法外层添加一层wrappers方法.举例说明, wrappers方法可以记录数据库查询的数量, 计算查询持续的事件, 为查询记录日志, 甚至可以阻止查询的执行(例如在渲染使用了预取的数据的模板时确保没有数据库查询被执行).</p>
<p>装饰器是在 <a class="reference internal" href="../http/middleware.html"><span class="doc">middleware</span></a> 之后建模的--它们是可调用的，并把其他调用作为它们的参数之一。它们调用可调用函数来调用（可能是包装的）数据库查询，并且它们可以围绕这个调用做一些工作。然而，它们通过用户代码来创建和安装，因此不需要独立像中间件这样的独立文件。</p>
<p>wrapper方法的安装是在上下文管理器中完成的 -- 因此wrapper方法是暂时的, 也是针对于你代码里的某些特定逻辑的.</p>
<p>正如上面提到的, 一个使用wrapper方法的例子是阻塞查询的执行. 类似的代码为:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">blocker</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">&#39;No database access allowed here.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>它可以被用在视图里阻止来自模板的查询，如下所示：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connection</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">context</span> <span class="o">=</span> <span class="p">{</span><span class="o">...</span><span class="p">}</span>  <span class="c1"># Code to generate context with all data.</span>
    <span class="n">template_name</span> <span class="o">=</span> <span class="o">...</span>
    <span class="k">with</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute_wrapper</span><span class="p">(</span><span class="n">blocker</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">template_name</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
</pre></div>
</div>
<p>发给wrapper方法的参数是:</p>
<ul class="simple">
<li>&quot;execute&quot; -- 一个可以被执行的对象, 使用剩下的参数触发来执行查询.</li>
<li><code class="docutils literal notranslate"><span class="pre">sql</span></code> -- 一个 <code class="docutils literal notranslate"><span class="pre">str</span></code>，要发送到数据库的SQL 查询。</li>
<li><code class="docutils literal notranslate"><span class="pre">params</span></code> -- SQL命令行参数值的列表/二元组，或者列表集/二元组集的一个列表/二元组（如果包装过的调用是  <code class="docutils literal notranslate"><span class="pre">executemany()</span></code> 的话）。</li>
<li><code class="docutils literal notranslate"><span class="pre">many</span></code> -- 一个布尔值，标识最终的调用是否是 <code class="docutils literal notranslate"><span class="pre">execute()</span></code> 还是 <code class="docutils literal notranslate"><span class="pre">executemany()</span></code> （以及 <code class="docutils literal notranslate"><span class="pre">params</span></code> 是否是一个值系列，还是一系列值的序列）。</li>
<li><code class="docutils literal notranslate"><span class="pre">context</span></code> -- 一个字典，包含带有关于调用上下文的数据。</li>
</ul>
<p>使用这个参数，稍微复杂一点的阻塞函数包含在错误信息中的连接名：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">blocker</span><span class="p">(</span><span class="n">execute</span><span class="p">,</span> <span class="n">sql</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">many</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
    <span class="n">alias</span> <span class="o">=</span> <span class="n">context</span><span class="p">[</span><span class="s1">&#39;connection&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">alias</span>
    <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s2">&quot;Access to database &#39;</span><span class="si">{}</span><span class="s2">&#39; blocked here&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">alias</span><span class="p">))</span>
</pre></div>
</div>
<p>有关更完整的例子，一个查询日志器看起来像这样：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>

<span class="k">class</span> <span class="nc">QueryLogger</span><span class="p">:</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">queries</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">execute</span><span class="p">,</span> <span class="n">sql</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">many</span><span class="p">,</span> <span class="n">context</span><span class="p">):</span>
        <span class="n">current_query</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;sql&#39;</span><span class="p">:</span> <span class="n">sql</span><span class="p">,</span> <span class="s1">&#39;params&#39;</span><span class="p">:</span> <span class="n">params</span><span class="p">,</span> <span class="s1">&#39;many&#39;</span><span class="p">:</span> <span class="n">many</span><span class="p">}</span>
        <span class="n">start</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">execute</span><span class="p">(</span><span class="n">sql</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">many</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="n">current_query</span><span class="p">[</span><span class="s1">&#39;status&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;error&#39;</span>
            <span class="n">current_query</span><span class="p">[</span><span class="s1">&#39;exception&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">e</span>
            <span class="k">raise</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">current_query</span><span class="p">[</span><span class="s1">&#39;status&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;ok&#39;</span>
            <span class="k">return</span> <span class="n">result</span>
        <span class="k">finally</span><span class="p">:</span>
            <span class="n">duration</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">monotonic</span><span class="p">()</span> <span class="o">-</span> <span class="n">start</span>
            <span class="n">current_query</span><span class="p">[</span><span class="s1">&#39;duration&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">duration</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">queries</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">current_query</span><span class="p">)</span>
</pre></div>
</div>
<p>要使用它，你可以创建一个日志器对象，并且将其作为装饰器来安装：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">connection</span>

<span class="n">ql</span> <span class="o">=</span> <span class="n">QueryLogger</span><span class="p">()</span>
<span class="k">with</span> <span class="n">connection</span><span class="o">.</span><span class="n">execute_wrapper</span><span class="p">(</span><span class="n">ql</span><span class="p">):</span>
    <span class="n">do_queries</span><span class="p">()</span>
<span class="c1"># Now we can print the log.</span>
<span class="nb">print</span><span class="p">(</span><span class="n">ql</span><span class="o">.</span><span class="n">queries</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-connection-execute-wrapper">
<span id="connection-execute-wrapper"></span><h2><code class="docutils literal notranslate"><span class="pre">connection.execute_wrapper()</span></code><a class="headerlink" href="#connection-execute-wrapper" title="永久链接至标题">¶</a></h2>
<dl class="method">
<dt id="django.db.backends.base.DatabaseWrapper.execute_wrapper">
<code class="descname">execute_wrapper</code>(<em>wrapper</em>)<a class="headerlink" href="#django.db.backends.base.DatabaseWrapper.execute_wrapper" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>返回一个上下文管理器，当进入时，会安装一个围绕数据库查询执行的装饰器，当离开时，会移除这个装饰器。装饰器是在本地线程的连接对象上安装的。</p>
<p><code class="docutils literal notranslate"><span class="pre">wrapper</span></code> 是一个带有五个参数的可调用函数。它在上下文管理器的范围内被每个查询调用，带着上面所述的五个参数 <code class="docutils literal notranslate"><span class="pre">execute</span></code>, <code class="docutils literal notranslate"><span class="pre">sql</span></code>, <code class="docutils literal notranslate"><span class="pre">params</span></code>, <code class="docutils literal notranslate"><span class="pre">many</span></code>, and <code class="docutils literal notranslate"><span class="pre">context</span></code> 。它预计会调用 <code class="docutils literal notranslate"><span class="pre">execute(sql,</span> <span class="pre">params,</span> <span class="pre">many,</span> <span class="pre">context)</span></code> ，并且返回那个调用的返回值。</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">数据库工具</a><ul>
<li><a class="reference internal" href="#connection-execute-wrapper"><code class="docutils literal notranslate"><span class="pre">connection.execute_wrapper()</span></code></a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="optimization.html"
                        title="上一章">数据库访问优化</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="examples/index.html"
                        title="下一章">模型关联 API 用法示例</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/db/instrumentation.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="optimization.html" title="数据库访问优化">previous</a>
     |
    <a href="../index.html" title="使用 Django" accesskey="U">up</a>
   |
    <a href="examples/index.html" title="模型关联 API 用法示例">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>